<?php


namespace App\Admin\Controllers;


use App\Admin\Repositories\Homepage;
use App\Service\MailService;
use Dcat\Admin\Admin;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class HomePageController extends AdminController
{
    public function index(Content $content)
    {
        app()->setLocale('zh-CN');
        return $content
            ->body($this->grid())
            ->header('首页配置');
    }

    protected function grid()
    {
        return Grid::make(new Homepage(), function (Grid $grid) {
            $grid->column('id', 'ID')->sortable();
            $grid->model()->orderByRaw("FIELD(state, 3, 2, 0, 1)")->orderBy('id','desc');

            $grid->column('name', '标题');
            $grid->column('linkurl','链接地址')->width('10%')->display(function ($linkurl) {
                if (!$linkurl) return '-';

                $shorturl = "查看链接";

                return <<<HTML
<span class="view-full-linkurl"
      data-content="{$linkurl}"
      style="cursor: pointer; color: #0022ff; border-bottom: 1px dashed #0022ff;">
    {$shorturl}
</span>
HTML;
            });;
            $grid->column('image1', '图一')->display(function ($image1) {
                return '<img src="' . $image1 . '" style="max-width:80px; max-height:80px; object-fit:contain;">';
            });
            $grid->column('image2', '图二')->display(function ($image2) {
                return '<img src="' . $image2 . '" style="max-width:80px; max-height:80px; object-fit:contain;">';
            });

            $grid->column('orid', '排序')->sortable();
            $grid->column('issue_time', '公开时间');

            $grid->column('state', '审核状态')->width("10%")->display(function ($type) {
                $types = [
                    0=>'已修改',
                    1=>'已公开',
                    2=>'已拒绝',
                    3=>'审核中'
                ];
                return $types[$type];
            });
            $grid->column('reason', '拒绝理由')->width("10%")->display(function ($reason) {
                if (!$reason) return '-';

                if ($this->state != 2) return '-';
                $shortReason = "点击查看";

                return <<<HTML
<span class="view-full-reason"
      data-content="{$reason}"
      style="cursor: pointer; color: #0022ff; border-bottom: 1px dashed #0022ff;">
    {$shortReason}
</span>
HTML;
            });

            $grid->column('actions', '提交&审核')->width('10%')->display(function () {
                $state = $this->state;
                $id = $this->id;

                if ($state == 0) {
                    return <<<HTML
<button class="btn btn-sm btn-primary submit-action"
        data-id="{$id}"
        style="padding: 3px 8px; font-size: 12px; line-height: 1.5; border-radius: 3px">
    <i class="feather icon-send"></i> 提交
</button>
HTML;
                }

                if ($state == 3) {
                    return <<<HTML
<div style="display: flex; gap: 5px;">
    <button class="btn btn-sm btn-success approve-action"
            data-id="{$id}"
            style="padding: 3px 8px; font-size: 12px; line-height: 1.5; border-radius: 3px">
        <i class="feather icon-check"></i>
    </button>
    <button class="btn btn-sm btn-danger reject-action"
            data-id="{$id}"
            style="padding: 3px 8px; font-size: 12px; line-height: 1.5; border-radius: 3px">
        <i class="feather icon-x"></i>
    </button>
</div>
HTML;
                }

                return <<<HTML
<button disabled
        class="btn btn-sm btn-light"
        style="padding: 3px 8px; font-size: 12px; line-height: 1.5; border-radius: 3px">
    <i class="feather icon-send"></i> 提交
</button>
HTML;
            });

            $submitUrl = route('admin.home.submit');
            $approveUrl = route('admin.home.approve');
            $rejectUrl = route('admin.home.reject');

            Admin::html(<<<HTML
<div class="modal fade" id="reject-reason-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">拒绝理由</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>请输入拒绝理由（最多500字符）</label>
                    <textarea id="reject-reason-input" class="form-control" rows="5" maxlength="500"></textarea>
                    <div id="reject-reason-error" class="text-danger" style="display: none; margin-top: 5px;"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirm-reject-btn">确认拒绝</button>
            </div>
        </div>
    </div>
</div>

<!-- 查看完整拒绝理由的模态框 -->
<div class="modal fade" id="view-reason-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">拒绝理由详情</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <p id="view-reason-content" style="word-wrap: break-word; white-space: pre-wrap;"></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 查看完整链接的模态框 -->
<div class="modal fade" id="view-linkurl-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">完整链接地址</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <p id="view-linkurl-content" style="word-wrap: break-word; white-space: pre-wrap;"></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
HTML
            );

            Admin::script(<<<JS
$(document).off('click', '.submit-action').on('click', '.submit-action', function(e) {
    handleButtonAction(e, this, '{$submitUrl}', '确定要提交审核吗？');
});

$(document).off('click', '.approve-action').on('click', '.approve-action', function(e) {
    handleButtonAction(e, this, '{$approveUrl}', '确定要审核通过吗？');
});

$(document).off('click', '.reject-action').on('click', '.reject-action', function(e) {
    e.stopPropagation();
    e.preventDefault();

    var id = $(this).data('id');
    var button = $(this);
    var originalHtml = button.html();

    $('#reject-reason-modal').data('id', id);
    $('#reject-reason-modal').data('button', button);
    $('#reject-reason-modal').data('originalHtml', originalHtml);

    $('#reject-reason-input').val('');
    $('#reject-reason-error').hide().text('');

    $('#reject-reason-modal').modal('show');
});

$(document).on('click', '.view-full-reason', function() {
    var content = $(this).data('content');
    $('#view-reason-content').text(content);
    $('#view-reason-modal').modal('show');
});
$(document).on('click', '.view-full-linkurl', function() {
    var content = $(this).data('content');
    $('#view-linkurl-content').text(content);
    $('#view-linkurl-modal').modal('show');
});

$('#confirm-reject-btn').off('click').on('click', function() {
    var reason = $('#reject-reason-input').val().trim();
    var errorMsg = $('#reject-reason-error');

    if (!reason) {
        errorMsg.text('拒绝理由不能为空').show();
        return;
    }

    var id = $('#reject-reason-modal').data('id');
    var button = $('#reject-reason-modal').data('button');
    var originalHtml = $('#reject-reason-modal').data('originalHtml');

    $(this).prop('disabled', true);
    button.html('<i class="fa fa-spinner fa-spin"></i> 处理中').prop('disabled', true);

    $.ajax({
        url: '{$rejectUrl}',
        type: 'POST',
        data: {
            id: id,
            reason: reason,
            _token: Dcat.token
        },
        success: function(response) {
            $('#reject-reason-modal').modal('hide');
            $('#confirm-reject-btn').prop('disabled', false);

            if (response.status) {
                Dcat.success(response.message || '拒绝成功');
                Dcat.reload();
            } else {
                Dcat.error(response.message || '操作失败');
                button.html(originalHtml).prop('disabled', false);
            }
        },
        error: function(xhr) {
            $('#reject-reason-modal').modal('hide');

            $('#confirm-reject-btn').prop('disabled', false);
            button.html(originalHtml).prop('disabled', false);

            var message = '服务器错误: ' + xhr.status;
            if (xhr.responseJSON && xhr.responseJSON.message) {
                message = xhr.responseJSON.message;
            }
            Dcat.error(message);
        }
    });
});

$('#reject-reason-modal').on('hidden.bs.modal', function () {
    var button = $(this).data('button');
    var originalHtml = $(this).data('originalHtml');

    if (button && originalHtml) {
        button.html(originalHtml).prop('disabled', false);
    }

    $('#confirm-reject-btn').prop('disabled', false);
});

function handleButtonAction(e, buttonElement, url, confirmText) {
    e.stopPropagation();
    e.preventDefault();

    var id = $(buttonElement).data('id');
    var button = $(buttonElement);
    var originalHtml = button.html();

    button.html('<i class="fa fa-spinner fa-spin"></i> 处理中');
    button.prop('disabled', true);

    Dcat.confirm(confirmText, null, function() {
        $.ajax({
            url: url,
            type: 'POST',
            data: {
                id: id,
                _token: Dcat.token
            },
            success: function (response) {
                if (response.status) {
                    Dcat.success(response.message || '操作成功');
                    Dcat.reload();
                } else {
                    Dcat.error(response.message || '操作失败');
                    button.html(originalHtml).prop('disabled', false);
                }
            },
            error: function (xhr) {
                var message = '服务器错误: ' + xhr.status + ' ' + xhr.statusText;
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                }
                Dcat.error(message);
                button.html(originalHtml).prop('disabled', false);
            }
        });
    }, function() {
        button.html(originalHtml).prop('disabled', false);
    });
}
JS
            );

            $grid->column('preview', '预览')->width('10%')->display(function () {
                $id = $this->id;

                $pcUrl = env('PREVIEW_URL') . "/preview?type=1&page=1";
                $mobileUrl = env('PREVIEW_URL') . "/preview?type=2&page=1";

                return <<<HTML
<div class="btn-group">
    <button class="btn btn-sm btn-primary pc-preview" data-url="{$pcUrl}">
        <i class="fa fa-desktop"></i>
    </button>
    <button class="btn btn-sm btn-success mobile-preview" data-url="{$mobileUrl}">
        <i class="fa fa-mobile"></i>
    </button>
</div>
HTML;
            });
            Admin::script(<<<JS
$(document).on('click', '.pc-preview', function () {
    let url = $(this).data('url');
    window.open(url, '_blank');
});

$(document).on('click', '.mobile-preview', function () {
    let url = $(this).data('url');
    window.open(url, '_blank');
});
JS);

            $grid->disableViewButton();
            $grid->disableRowSelector();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        app()->setLocale('zh-CN');
        return Form::make(new Homepage(), function (Form $form) {
            $form->display('id', 'ID');

            $form->datetime('issue_time', '公开时间')->format('YYYY-MM-DD HH:mm:ss')
                ->default($form->model()->issue_time ?? now()->format('Y-m-d H:i:s'))->required();

            $form->text('name', '名称')->required();
            $form->text('linkurl', '链接')->required();
            $form->text('orid', '排序')->rules('required|integer',['required'=>'排序值不能为空','integer'=>'排序值必须是非负整数'])->required();
            $form->image('image1', '图片一（PC端）')
                ->disk('remote_storage')
                ->move('/assets/img/cms/new_cms_img/images/' . date('Y/m/d'))->retainable()
                ->help('宽1424px高598px以内，500KB以内')->required();
            $form->image('image2', '图片二（手机端）')
                ->disk('remote_storage')
                ->move('/assets/img/cms/new_cms_img/images/' . date('Y/m/d'))->retainable()
                ->help('宽671px高720px以内，500KB以内')->required();

            $form->html(<<<HTML
<script>
Dcat.ready(function() {
    $(document).on('click', '.file-input-remove', function(e) {
        e.stopPropagation();
        const _this = $(this);

        Dcat.confirm('文件删除会直接自动保存，请确认并谨慎操作', function() {
            _this.closest('.file-input')
                .find('input[type=hidden][name$="[delete]"]')
                .val(1);

            _this.closest('.file-input').find('.file-preview').remove();
            _this.closest('.file-input').find('.file-actions').remove();
            Dcat.success('图片已标记删除');
        });

        return false;
    });
});
</script>
HTML
            );

            $form->hidden('state')->value(0);
            $form->hidden('operator_id')->value(0);

            $form->saving(function () use ($form) {
                $form->state = 0;
                $user = Admin::user();
                $form->operator_id = $user->id;
            });
            $form->footer(function ($footer) {

                $footer->disableViewCheck();

                $footer->disableEditingCheck();
                $footer->disableViewCheck();
                $footer->disableReset();
            });
            $form->disableViewButton();
        });
    }

    public function destroy($id)
    {
        $menu = \App\Models\Homepage::withoutGlobalScope('not_deleted')->findOrFail($id);
        $menu->delete();

        return response()->json([
            'status'  => true,
            'message' => '删除成功',
        ]);
    }

    /**
     * 显示指定菜谱的详情
     *
     * @param mixed $id
     * @return \Dcat\Admin\Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Homepage(), function (Show $show) {
            $show->field('id', 'ID');
            $show->field('name', '名称');
            $show->field('linkurl', '链接地址');
            $show->field('image1', '图片一')->image();
            $show->field('image2', '图片二')->image();
        });
    }

    // 提交处理方法
    public function submit(Request $request)
    {
        $id = $request->input('id');
        $model = \App\Models\Homepage::find($id);

        if (!$model) {
            return response()->json([
                'status' => false,
                'message' => '记录不存在'
            ], 404);
        }

        if ($model->state != 0) {
            return response()->json([
                'status' => false,
                'message' => '只有草稿状态才能提交'
            ], 400);
        }

        $model->state = 3;
        $user = Admin::user();
        $model->operator_id = $user->id;
        $model->save();

        $mailService = new MailService();
        $pcUrl = env('PREVIEW_URL') . "/preview?type=1&page=1";
        $mobileUrl = env('PREVIEW_URL') . "/preview?type=2&page=1";
        $adminInfo = DB::table('admin_users')->where('id','=',$model->operator_id)->first(['id','name']);
        $adminList = DB::table('admin_users as user')->join('admin_role_users as role','user.id','=','role.user_id')
            ->where('role.role_id','=','2')->get(['user.email'])
            ->map(function ($item) {
                return (array)$item;
            })
            ->toArray();
        $emailList = array_column($adminList,'email');
        $mailService->sendOperationConfirmation($adminInfo->name,'',$model->issue_time,'',$pcUrl,$mobileUrl,3,$emailList,'【公开确认请求】首页轮播图');

        return response()->json([
            'status' => true,
            'message' => '提交成功，状态已更新为审核中'
        ]);
    }

    public function approve(Request $request)
    {
        $id = $request->id;
        $model = \App\Models\Homepage::find($id);

        if (!$model) {
            return response()->json(['status' => false, 'message' => '记录不存在']);
        }
        $user = Admin::user();
        $isAdmin = $user->roles()->where('id', 2)->exists();

        if (!$isAdmin) {
            return response()->json([
                'status' => false,
                'message' => '无权操作：仅管理员可执行此操作'
            ], 403);
        }

        $model->state = 1;
        $model->auditor_id = $user->id;
        $model->save();

        $mailService = new MailService();
        $pcUrl = env('PREVIEW_URL') . "/preview?type=1&page=1";
        $mobileUrl = env('PREVIEW_URL') . "/preview?type=2&page=1";
        $operatorInfo = DB::table('admin_users')->where('id','=',$model->operator_id)->first(['id','name']);
        $auditorInfo = DB::table('admin_users')->where('id','=',$user->id)->first(['id','name']);
        $adminList = DB::table('admin_users as user')->join('admin_role_users as role','user.id','=','role.user_id')
            ->where('role.role_id','=','2')
            ->orWhere('user.id','=',$model->operator_id)->get(['user.email'])
            ->map(function ($item) {
                return (array)$item;
            })
            ->toArray();
        $emailList = array_column($adminList,'email');
        $mailService->sendOperationConfirmation($operatorInfo->name,$auditorInfo->name,$model->issue_time,'',$pcUrl,$mobileUrl,1,$emailList,'【公开通知】首页轮播图');

        return response()->json(['status' => true, 'message' => '审核已通过']);
    }

    public function reject(Request $request)
    {
        $id = $request->id;
        $reason = $request->input('reason', '');
        $model = \App\Models\Homepage::find($id);

        if (!$model) {
            return response()->json(['status' => false, 'message' => '记录不存在']);
        }
        $user = Admin::user();
        $isAdmin = $user->roles()->where('id', 2)->exists();

        if (!$isAdmin) {
            return response()->json([
                'status' => false,
                'message' => '无权操作：仅管理员可执行此操作'
            ], 403);
        }

        $model->state = 2;
        $model->reason = $reason;
        $model->auditor_id = $user->id;
        $model->save();

        $mailService = new MailService();
        $pcUrl = env('PREVIEW_URL') . "/preview?type=1&page=1";
        $mobileUrl = env('PREVIEW_URL') . "/preview?type=2&page=1";
        $operatorInfo = DB::table('admin_users')->where('id','=',$model->operator_id)->first(['id','name']);
        $auditorInfo = DB::table('admin_users')->where('id','=',$user->id)->first(['id','name']);
        $adminList = DB::table('admin_users as user')->join('admin_role_users as role','user.id','=','role.user_id')
            ->where('role.role_id','=','2')
            ->orWhere('user.id','=',$model->operator_id)->get(['user.email'])
            ->map(function ($item) {
                return (array)$item;
            })
            ->toArray();
        $emailList = array_column($adminList,'email');
        $mailService->sendOperationConfirmation($operatorInfo->name,$auditorInfo->name,date('Y-m-d H:i:s'),$reason,$pcUrl,$mobileUrl,2,$emailList,'【审核拒绝】首页轮播图');

        return response()->json(['status' => true, 'message' => '审核已拒绝']);
    }

}
